<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\DistributeTask as DistributeTaskModer;
use app\admin\model\DistributeTaskLog;
use app\admin\model\OperationTask;
use app\admin\model\DistributeStatistics;
use app\admin\model\User;
use app\api\controller\Withdraw as WithdrawApi;
use app\admin\model\Payment;
use app\admin\model\Product;
use app\admin\model\TemplateImgLog;
use app\admin\model\Shop;
use app\admin\model\ShopPriceLog;
use app\admin\model\SArea;
use app\admin\model\UserAddress;
use app\admin\model\Withdraw;
use app\admin\model\DistributeTaskInvite;
use app\admin\model\ProductCategory;
use app\admin\model\TaskCategoryList;
use app\admin\model\Area;
use app\common\model\Config;
use app\admin\model\TaskScheduled;
use think\Db;
use think\exception\PDOException;
use think\Exception;
use think\Session;
use fast\Date;

/**
 * 任务管理
 *
 * @icon   fa fa-list
 */
class DistributeTask extends Backend
{

    protected $model = null;
    protected $group_id = null;
    protected $admin = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new DistributeTaskModer();
        $admin = Session::get('admin');
        $group_id = db('auth_group_access')->where(['uid'=>$admin['id']])->value('group_id');
        $this->group_id = $group_id;
        $this->admin = $admin;
        $this->assignconfig('group_id', $group_id);
        $this->view->assign('group_id', $group_id);
        $this->view->assign('admin', $admin);
    }

    /**
     * 查看
     */
    public function index()
    {
       
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $zi = $this->request->request('zi','');
        $this->assignconfig('zi', $zi);
        
        $status = $this->request->request('status','');
        $this->assignconfig('status', $status);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $where1 = [];
            if($this->group_id == 6){
                $where1['type'] = $this->admin['nickname'];
            }
            if($this->group_id == 7){
                $where1['admin_id'] = $this->admin['id'];
            }
            // if($status){
            //     $where1['status'] = $status;
            // }
            $list = $this->model
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {

                //判断ip是否重复
                if($v['ip']){
                    $ips = DistributeTaskModer::whereTime('receive_time', 'today')->where(['ip'=>$v['ip']])->count();
                    if($ips <= 1){
                        $v['ip'] = '';
                    }else{
                        $v['ip'] =  $v['ip'].'('.$ips.')';
                    }
                }
                $info =  User::field('nickname,mobile,is_accept_yx')->where(['id'=>$v['user_id']])->find();
                $v['nickname'] = $info['nickname'];
                $v['mobile'] = $info['mobile'];
                $v['is_accept_yx'] = $info['is_accept_yx'];
                $v['end_time'] = $v['end_time']?$v['end_time']:'';
                if (strpos($v['user_content'], 'https://') !== false) {
                    $v['user_content_1'] = $v['user_content'];
                    $v['user_content'] =  '查看链接';
                    $v['user_content_status'] = 1;
                }elseif(strpos($v['user_content'], 'http://') !== false){
                    $urls = explode('http://',$v['user_content']);
                    if(!empty($urls[1])){
                        $v['user_content'] = 'http://'.$urls[1];
                    }
                    $v['user_content_status'] = 2;
                }else{
                    $v['user_content_status'] = 0;
                }

                if($v['task_type'] == 4){
                    if(strpos($v['title'], 'http://') !== false){
                        $urls = explode('http://',$v['title']);
                        if(!empty($urls[1])){
                            $v['title'] = 'http://'.$urls[1];
                        }
                    }
                }

                if($v['statistics_num'] == 0){
                    $v['statistics_num'] = '未回传';
                }
                $v['imgs'] = str_replace("http://www.sulamarketing.com", "https://oa.yuxiang123.cn", $v['imgs']);
                
                if (strpos($v['imgs'], 'https') === false && strpos($v['imgs'], 'http') === false) {
                    $v['imgs'] = str_replace('/uploads', 'https://yuxiangapp.oss-cn-guangzhou.aliyuncs.com/uploads', $v['imgs']);
                }

                // if(empty($v['appuid']) && $v['user_content']){
                //     $title = $v['user_content'];
                //     $datas = [];
                //     if (strpos($title, 'https://') !== false) {
                //         $res = explode('?',$title);
                //         if(empty($res[0])){
                //             continue;                            
                //         }
                //         $datas = explode('/',$res[0]);
                //     }elseif(strpos($title, 'http://') !== false){
                //         $res = explode('http://',$title);
                //         if(empty($res[1])){
                //             continue;        
                //         }
                //         $res = explode('，',$res[1]);
                //         $headers = get_headers('http://'.$res[0]); //获取重定向之后的url
                //         foreach ($headers as $vs) {
                //             if (strpos($vs, 'Location') !== false) {
                //                 $res = explode('?',$vs);
                //                 if(empty($res[0])){
                //                     continue;
                //                 }
                //                 $datas = explode('/',$res[0]);
                //             }
                //         }
                //     }
                //     if(count($datas) < 4){
                //         continue;
                //     }
                //     $res = DistributeTaskModer::where(['appuid'=>$datas[count($datas)-1]])->find();
                //     $update = [];
                //     if($res){
                //         $update['is_repetition'] = 1;
                //         $v['is_repetition'] = 1;
                //     }
                //     $update['appuid'] = $datas[count($datas)-1];
                //     DistributeTaskModer::where(['id'=>$v['id']])->update($update);
                // }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $statistics_num = 0;
        $balance_num = 0;
        $yesterday_num = 0;
        if($this->group_id == 6){
            $statistics_num =  $this->model->where(['type'=>$this->admin['nickname']])->sum('statistics_num');
            $shop=  Shop::where(['admin_id'=>$this->admin['id']])->find();
            $balance_num = $shop['balance'];
            $yesterday_num =  ShopPriceLog::where(['shop_id'=>$shop['id'],'type'=>['neq',2]])->whereTime('add_time', 'yesterday')->sum('price');
            if($yesterday_num > 0){
                $yesterday_num = 0;
            }
            if($this->admin['id'] == 29){
                $column = [];
                $time_info = date('Y-m');
                if($time_info == '2024-04'){
                    $time_info = '2024-04-08';
                }
                $starttime = strtotime($time_info);
                //$starttime = Date::unixtime('day', -6);
                $endtime = Date::unixtime('day', 0, 'end');
                $joinlist = Db("shop_price_log")->where('add_time', 'between time', [$starttime, $endtime])
                ->where(['shop_id'=>$shop['id'],'type'=>['neq',2]])
                ->field('add_time,  sum(price) AS nums, DATE_FORMAT(FROM_UNIXTIME(add_time), "%Y-%m-%d") AS join_date')
                ->group('join_date')
                ->select();
                
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("Y-m-d", $time);
                    $time += 86400;
                }
                $userlist = array_fill_keys($column, 0);
                foreach ($joinlist as $k => $v) {
                    if($v['nums'] > 0){
                        $userlist[$v['join_date']]  = 0;
                    }else{
                        $userlist[$v['join_date']] = $v['nums']*-1;
                    }
                    
                }
                $this->assignconfig('column', array_keys($userlist));
                $this->assignconfig('userdata', array_values($userlist));
            }


        }
        $this->view->assign('statistics_num', $statistics_num);
        $this->view->assign('balance_num', $balance_num*1);
        $this->view->assign('yesterday_num', $yesterday_num*-1);




        return $this->view->fetch();
    }

    //已删除订单列表
    public function del_list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $zi = $this->request->request('zi','');
        $this->assignconfig('zi', $zi);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');

            $time = time()-(30*24*3600);
            $time1 = strtotime(date('Y-m-d',$time));
            $time2 = $time1+(24*3600);
            $where1 = ['add_time' => ['between', [$time1, $time2]],'status'=>3,'is_del'=>0,'is_erroneous_judgement'=>0];
           // $where1 = ['is_del_old'=>1,'is_erroneous_judgement'=>0,'is_del'=>0];
            $list = $this->model
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                $user =  User::field('nickname,mobile,is_accept_yx')->where(['id'=>$v['user_id']])->find();
                $v['nickname'] = $user['nickname'];
                $v['mobile'] = $user['mobile'];
                $v['is_accept_yx'] = $user['is_accept_yx'];
                $v['end_time'] = $v['end_time']?$v['end_time']:'';
                if (strpos($v['user_content'], 'https://') !== false) {
                    $v['user_content_1'] = $v['user_content'];
                    $v['user_content'] =  '查看链接';
                    $v['user_content_status'] = 1;
                }elseif(strpos($v['user_content'], 'http://') !== false){
                    $urls = explode('http://',$v['user_content']);
                    if(!empty($urls[1])){
                        $v['user_content'] = 'http://'.$urls[1];
                    }
                    $v['user_content_status'] = 2;
                }else{
                    $v['user_content_status'] = 0;
                }
                if($v['statistics_num'] == 0){
                    $v['statistics_num'] = '未回传';
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $category_list = TaskCategoryList::select();
            $this->view->assign('category_list', $category_list);
            $user_list =  User::field("nickname,id")->where(['is_task'=>1])->select();
            $this->view->assign('user_list', $user_list);
            if($this->group_id == 7){
                $type_arr = Shop::where(['status'=>1,'id'=>['in',$this->admin['shop_ids']]])->column('name');
            }else{
                $type_arr = Shop::where(['status'=>1])->column('name');
            }
           
            $this->view->assign('type_arr', $type_arr);
            //查询所有的省
            $AreaList = Area::field("name")->where(['pid'=>0])->select();
            $this->view->assign('AreaList', $AreaList);
            $is_province = Shop::where(['admin_id'=>$this->admin['id']])->value('is_province');
            $this->view->assign('is_province', $is_province);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $params = $this->preExcludeFields($params);
        if($params['task_type'] == 4){  //评论任务
            if(empty($params['tl_title'])){
                $this->error('小红书链接不可为空');
            }
            if(empty($params['tl_content'])){
                $this->error('评论内容不可为空');
            }
            if(empty($params['tl_num'])){
                $this->error('生成评论数量不可为空');
            }
            for ($i=0; $i < $params['tl_num']; $i++) { 
                $result = false;
                if($this->group_id == 6){ //商户上传任务
                    //查询商户信息
                    $shop  = Shop::where(['admin_id'=>$this->admin['id'],'status'=>1])->find();
                    if(!$shop){
                        $this->error('商户信息错误,请联系管理员');
                    }
                    //商户上传任务操作
                    $result = shop_add_comment_task($params,$shop);
                }
                if ($result === false) {
                    $this->error(__('No rows were inserted'));
                }
            }

           
            $this->success();
        }

        //查询是录入的还是选择的
        if(!empty($params['category1'])){
            $chtegory_id = TaskCategoryList::insertGetId(['name'=>$params['category1'],'type'=>$params['type']]);
            unset($params['category1']);
            $params['category'] = $chtegory_id;
        }elseif(!empty($params['category'][0])){
            $params['category'] = $params['category'][0];
            unset($params['category1']);
        }else{
            if($this->group_id == 6){ //商户上传任务
                $params['category'] = $this->admin['username'];
                $params['type'] = $this->admin['username'];
            }else{
                $this->error('类目不可为空');
            }
        }
        if(!empty($params['province'][0])){
            $params['province'] = $params['province'][0];
        }
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if(empty($params['title'])){
            $this->error('标题不可为空');
        }
        if(empty($params['content'])){
            $this->error('内容不可为空');
        }
        if(!empty($params['zn_imgs'])){
            $params['imgs'] = $params['zn_imgs'];
        }
        if(empty($params['imgs'])){
            $this->error('图片不可为空');
        }
        $result = false;
        Db::startTrans();
        try {
            if($this->group_id == 6){ //商户上传任务
                //查询商户信息
                $shop  = Shop::where(['admin_id'=>$this->admin['id'],'status'=>1])->find();
                if(!$shop){
                    $this->error('商户信息错误,请联系管理员');
                }
                //商户上传任务操作
                $result = shop_add_task($params,$shop);
                if ($result === false) {
                    Db::rollback();
                    $this->error('账号余额不足');
                }
            }else{
                $title = explode('=',$params['title']);
                $content = explode('=',$params['content']);
                $imgs = explode(',',$params['imgs']);
                if($params['type'] == '电事聚小红书' && $params['imgs1']){
                    $imgs1 = explode(',',$params['imgs1']);
                }
                if(count($title) != count($content)  || count($imgs) < count($title)){
                    $this->error('标题/内容/图片对应数量错误');
                }
                $product_id = empty($params['product_id']) ? 0 : $params['product_id'];
                //查询商户信息
                $shop  = Shop::where(['name'=>$params['type'],'status'=>1])->find();
                if($shop && $shop['is_admin_gl'] == 1){
                    foreach ($title as $k=>$v) {
                        $data = [
                            'title'=>$title[$k],
                            'content'=>$content[$k],
                            'imgs'=> count($title) > 1 ? $imgs[$k] : $params['imgs'],
                            'beizhu'=>!empty($params['beizhu']) ? $params['beizhu'] : '',
                            'category'=>$params['category'],
                            'province'=>!empty($params['province']) ? $params['province'] : '',
                        ];
                        //商户上传任务操作
                        $shop  = Shop::where(['id'=>$shop['id']])->find();
                        $admin_id = 0;
                        if($this->group_id == 7){
                            $admin_id = $this->admin['id'];
                        }

                        $result = shop_add_task($data,$shop,$admin_id);
                        if ($result === false){
                            Db::commit();
                            $this->error('商户余额不足');
                        }
                    }
                }else{
                    foreach ($title as $k=>$v) {
                        if($params['type'] == '电事聚小红书'){
                            $arr = [
                                'add_time' => time(),
                                'title'=>$title[$k],
                                'content'=>$content[$k],
                                'task_type'=>$params['task_type'] ? $params['task_type'] : 1,
                                'type'=>$params['type'] ,
                                'category'=>$params['category'] ,
                                'beizhu'=>!empty($params['beizhu']) ? $params['beizhu'] : '',
                                'character_type'=> 1,
                                'province'=>!empty($params['province']) ? $params['province'] : '',
                            ];
                            if(!empty($imgs1)){
                                $arr['imgs'] = count($title) > 1 ? $imgs[$k].','.$imgs1[$k] : $params['imgs'].','.$params['imgs1'];
                            }else{
                                $arr['imgs'] = count($title) > 1 ? $imgs[$k] : $params['imgs'];
                            }

                        }else{
                            $arr = [
                                'add_time' => time(),
                                'title'=>$title[$k],
                                'content'=>$content[$k],
                                'imgs'=> count($title) > 1 ? $imgs[$k] : $params['imgs'],
                                'product_id'=>$product_id,
                                'task_type'=>$params['task_type'] ? $params['task_type'] : 1,
                                'type'=>$params['type'] ,
                                'category'=>$params['category'] ,
                                'beizhu'=>!empty($params['beizhu']) ? $params['beizhu'] : '',
                                'character_type'=> 1,
                                'province'=>!empty($params['province']) ? $params['province'] : '',
                            ];
                        }
                        $arr['status'] = -3;
                        if($params['type'] == '余享小红书'){
                            $arr['task_status'] = 'distribute';
                        }else{
                            $arr['task_status'] = 'dianshiju';
                        }
                        if($this->group_id == 7){
                            $arr['admin_id'] = $this->admin['id'];
                        }
                        $result = DistributeTaskModer::insert($arr);
                    }
                    // $ids = User::where(['is_task_subscription'=>1])->column('id');
                    // if($ids){
                    //     $idss = DistributeTaskModer::where(['status'=>1,'user_id'=>['in',$ids]])->whereTime('receive_time', 'today')->column('user_id');
                    //     $arr_ids = [];
                    //     foreach ($ids as $v) {
                    //         if(!in_array($v,$idss)){
                    //             $arr_ids[] = $v;
                    //         }
                    //     }
                    //     if($arr_ids){
                    //         foreach ($arr_ids as $vs) {
                    //             //查看用户今天是否已经接单
                    //             $data = [
                    //                 "thing1"=>["value"=>'余享新任务已更新'],
                    //                 "time3"=>["value"=>date('Y-m-d H:i:s',time())]
                    //             ];
                    //             send_subscription($vs,'xF751UgAPsa4BajwBin-BU6lG1riuvJsNxNpIPGM28c','/subone/user/distribute_task',$data);
                    //         }
                    //     }
                    // }
                }
            }
            
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
 
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            if(!empty($values['is_task'])){
                $list = User::where(['id'=>['in',$ids],'is_task'=>-1])->select();
                foreach ($list as $v) {
                    //发送短信
                    send_mobile($v['mobile'],'SMS_464775823');
                    User::where(['id'=>$v['id']])->update(['is_task'=>1,'task_time'=>time()]);
                }
                $count = 1;
            }else{
                $list = [];
                if(!empty($values['is_read']) && $values['is_read'] == 1 ){
                    //检查
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->where(['is_read'=>0])->select();
                }elseif(isset($values['is_new_user']) && $values['is_new_user'] == 1){
                    //检查
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->where(['is_new_user'=>0])->select();
                }elseif(isset($values['is_new_user']) && $values['is_new_user'] == 0){
                    //检查
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->where(['is_new_user'=>1])->select();
                }elseif(isset($values['is_read']) && $values['is_read'] == 0){
                    //检查
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->where(['is_read'=>1])->select();
                   
                }elseif(isset($values['status']) && $values['status'] == 0){
                    //上架
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->where(['status'=>-3])->select();
                }elseif(isset($values['status']) && $values['status'] == -3){
                    //下架
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->where(['status'=>0])->select();
                    
                }
                foreach ($list as $item) {
                    $count += $item->allowField(true)->isUpdate(true)->save($values);
                }

                if(isset($values['status']) && $values['status'] == 0 && $count >= 5){
                    //发送订阅消息
                    $redis = redis_init();
                    $name = 'send_subscription_news';
                    $redis->set($name,1);
                    //send_task_subscription();
                }
               
                if(isset($values['status']) && $values['status'] == 3){
                    $count += 1;
                    //一键审核
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->where(['status'=>2])->select();
                    foreach ($list as $info) {
                        $id = $info['id'];
                        $userInfo = User::where(['id'=>$info['user_id']])->find(); 
                        if($info['task_status'] == 'pinglun' || $info['task_status'] == 'comment_num'){
                            $price = 0.5;
                        }else{
                            //查询佣金规则
                            if($info['type'] != '余享小红书'){
                                $configWhere = ['name'=>'dianshiju'];
                            }else{
                                $configWhere = ['name'=>'distribute'];
                            }
                            $config = Config::where($configWhere)->value('value');
                            $config = json_decode($config,true);
                            $price = 0;
                            if(!empty($config['award'])){
                                $awardArr = $config['award'];
                                $priceArr = $config['price'];
                                foreach ($awardArr as $k=>$award_arr) {
                                    if(count($award_arr) == 1){
                                        if($info['statistics_num'] > $award_arr[0]){
                                            $price = $priceArr[$k];
                                        }
                                    }else{
                                        if($info['statistics_num'] >= $award_arr[0]  &&  $info['statistics_num'] <=  $award_arr[1]){
                                            $price = $priceArr[$k];
                                        }
                                    }
                                }
                            }else{
                                $price = $info['price'];
                            }
                        }
                        $res = DistributeTaskModer::where(['id'=>$id])->update(['status'=>3,'complete_time'=>time(),'price'=>$price]);
                        if(!$res){
                            Db::rollback();
                            $this->error('操作失败');
                        }

                        //查询是否是素材任务
                        $OperationTask = OperationTask::where(['status'=>0,'task_id'=>$id])->find();
                        if($OperationTask){
                            OperationTask::where(['id'=>$OperationTask['id']])->update(['title'=>$info['user_operation_title'],'content'=>$info['user_content'],'imgs'=>$info['user_imgs'],'status'=>1]);
                            if($OperationTask['issue_type'] == 1){
                                $price = 8;
                            }elseif($OperationTask['issue_type'] == 2){
                                $price = 6;
                            }elseif($OperationTask['issue_type'] == 3){
                                $price = 3;
                            }
                        }

                        //查看该用户是否是被邀请
                        $DistributeTaskInvite = DistributeTaskInvite::where(['invite_id'=>$info['user_id'],'status'=>0])->find();
                        if($DistributeTaskInvite){
                            DistributeTaskInvite::where(['id'=>$DistributeTaskInvite['id']])->update(['status'=>1,'price'=>2]);
        
                            $InviteUser = User::where(['id'=>$DistributeTaskInvite['user_id']])->find();
                            //记录佣金日志
                            $arr = [
                                'user_id'=>$InviteUser['id'],
                                'new_price'=>$InviteUser['task_price'],
                                'price'=>2,
                                'type'=>5,
                                'old_price'=>$InviteUser['task_price']+2,
                                'add_time'=>time()
                            ];
                            DistributeTaskLog::insert($arr);
                            User::where(['id'=>$InviteUser['id']])->update(['task_price'=>$InviteUser['task_price']+2]);
                        }
        
                        //通过审核后管理商户余额
                        $res = set_shop_task_price($info['id'],2);
                        
                        if($res['code'] == -1){
                            Db::rollback();
                            $this->error($res['msg']);
                        }
        
                        User::where(['id'=>$info['user_id']])->update(['task_price'=>$userInfo['task_price'] + $price]);
                        //记录佣金日志
                        $arr = [
                            'user_id'=>$info['user_id'],
                            'new_price'=>$userInfo['task_price'],
                            'price'=>$price,
                            'old_price'=>$userInfo['task_price']+$price,
                            'add_time'=>time()
                        ];
                        DistributeTaskLog::insert($arr);
                        
                        //发送短信
                        send_mobile($userInfo['mobile'],'SMS_464185599');
                    }
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }
    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function del_multi($ids = null)
    {
 
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            if(!empty($values['is_del'])){
                DistributeTaskModer::where(['id'=>['in',$ids]])->update(['is_del'=>1]);
                $count = 1;
            }elseif(!empty($values['is_erroneous_judgement'])){
                DistributeTaskModer::where(['id'=>['in',$ids]])->update(['is_erroneous_judgement'=>1]);
                $count = 1;
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    
    /**
     * 查看
     */
    public function user_index($ids = '')
    {
        $shop_id = $this->request->request('shop_id','');
        $this->assignconfig('shop_id', $shop_id);
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            if($shop_id){
                $shop = Shop::where(['id'=>$shop_id])->find();
                $list = $this->model
                    ->where($where)
                    ->where(['type'=>$shop['name']])
                    ->order($sort, $order)
                    ->paginate($limit);
            }else{
                $list = $this->model
                    ->where($where)
                    ->where(['user_id'=>$ids])
                    ->order($sort, $order)
                    ->paginate($limit);
            }
            foreach ($list as $k => &$v) {
                //判断是否已经开奖?
                $v['nickname'] = User::where(['id'=>$v['user_id']])->value('nickname');
                $v['end_time'] = $v['end_time']?$v['end_time']:'';
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    

    //接单人列表
    public function user_list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = User::where($where)
                ->where(['is_task'=>['in',['1','-1']]])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                //判断ip是否重复
                if($v['ip']){
                    $ips = User::where(['ip'=>$v['ip']])->count();
                    if($ips <= 1){
                        $v['ip'] = '';
                    }
                }
                $pid = DistributeTaskInvite::where(['invite_id'=>$v['id']])->value('user_id');
                if($pid){
                    $v['pid_nickname'] = User::where(['id'=>$pid])->value('nickname');
                }else{
                    $v['pid_nickname'] = '';
                }
                //$v['task_sum'] = $this->model->where(['user_id'=>$v['id'],'status'=>['neq',0]])->count();
                //$v['wc_task_sum'] = $this->model->where(['user_id'=>$v['id'],'status'=>3])->count();
                //$v['withdraw_sum'] = Withdraw::where(['user_id'=>$v['id'],'status'=>['neq','rejected']])->sum('money');
                //$v['handingfee_sum'] = Withdraw::where(['user_id'=>$v['id'],'status'=>['neq','rejected']])->sum('handingfee');
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    //任务自动上架计划任务
    public function task_scheduled_list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('name','',new TaskScheduled());
            $list = TaskScheduled::where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$v) {
                $v['category_name'] = TaskCategoryList::where(['id'=>$v['category_id']])->value('name');
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    //获取任务类目
    public function getTaskCategoryList()
    {
        $type = $this->request->request('type','');
        $category_list = TaskCategoryList::where(['type'=>$type])->select();
        return $category_list;
    }


    //任务自动上架计划任务添加
    public function task_scheduled_add()
    {
        if (false === $this->request->isPost()) {
            $category_list = TaskCategoryList::where(['type'=>'余享小红书'])->select();
            $this->view->assign('category_list', $category_list);
            $type_arr = Shop::where(['status'=>1])->column('name');
            $this->view->assign('type_arr', $type_arr);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if(!empty($params['category'])){
                $params['category_id'] = $params['category'][0];
            }
            unset($params['category']);
            $params['add_time'] = time();
            $result = TaskScheduled::insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    //任务自动上架计划任务编辑
    public function task_scheduled_edit($ids)
    {
        $row = TaskScheduled::where('id',$ids)->find();
        if (false === $this->request->isPost()) {
            $type_arr = Shop::where(['status'=>1])->column('name');
            $this->view->assign('type_arr', $type_arr);
            $category_list = TaskCategoryList::where(['type'=>$row['type']])->select();
            $this->view->assign('category_list', $category_list);

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if(!empty($params['category'])){
                $params['category_id'] = $params['category'][0];
            }
            unset($params['category']);
            $result = TaskScheduled::where(['id'=>$ids])->update($params);
            
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    //任务类目列表
    public function category_list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('name','',new TaskCategoryList());
            $list = TaskCategoryList::where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    //类目添加
    public function category_add()
    {
        if (false === $this->request->isPost()) {
            $type_arr = Shop::where(['status'=>1])->column('name');
            $this->view->assign('type_arr', $type_arr);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $params['name'] = str_replace('，', ',', $params['name']);
            $arr = explode(',',$params['name']);
           
            foreach ($arr as $v) {
                $params['name'] = $v;
                $result = TaskCategoryList::insert($params);
            }
            
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    //删除
    public function category_del($ids)
    {
        $result = TaskCategoryList::where(['id'=>$ids])->delete();
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //删除
    public function task_scheduled_del($ids)
    {
        $result = TaskScheduled::where(['id'=>$ids])->delete();
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    
    
    /**
     * 浏览统计列表
     */
    public function statistics_list($ids = '')
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('name,url','',new DistributeStatistics());
            $list = DistributeStatistics::where($where)
                ->order($sort, $order)
                ->paginate($limit);
            // foreach ($list as &$v) {
            //     $v['status'] = 1;
            //     if($v['type'] == 2){
            //         //查询该笔提现状态
            //         $info = Withdraw::where(['money'=>$v['price']*-1,'user_id'=>$v['user_id']])->order('id desc')->find();
            //         if($info && $info['status'] == 'created'){
            //             $v['status'] = '2';
            //         }elseif($info && $info['status'] == 'rejected'){
            //             $v['status'] = '-1';
            //         }
            //     }
            // }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加浏览数量
     *
     * @return string
     * @throws \think\Exception
     */
    public function statistics_add($ids = null)
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if(!empty($params['add_time'])){
                $params['add_time'] = strtotime($params['add_time']);
            }else{
                $params['add_time'] = time();
            }
            $result = DistributeStatistics::insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

     /**
     * 删除
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function statistics_del($ids = null)
    {
        $row = DistributeStatistics::where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $res = DistributeStatistics::where(['id'=>$ids])->delete();
        if (false === $res) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 接单人财务明细
     */
    public function withdraw_list($ids = '')
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = DistributeTaskLog::where($where)
                ->where(['user_id'=>$ids])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$v) {
                $v['status'] = 1;
                if($v['type'] == 2){
                    //查询该笔提现状态
                    $info = Withdraw::where(['money'=>$v['price']*-1,'user_id'=>$v['user_id']])->order('id desc')->find();
                    if($info && $info['status'] == 'created'){
                        $v['status'] = '2';
                    }elseif($info && $info['status'] == 'rejected'){
                        $v['status'] = '-1';
                    }
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 删除团长
     *
     * @return string
     * @throws \think\Exception
     */
    public function detele_user_tz($id = null)
    {
        $status = $this->request->request('status');
        $result = false;
        Db::startTrans();
        try {
            $result = User::where(['id'=>$id])->update(['task_status'=>$status]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
     /**
     * 禁止接收余享
     *
     * @return string
     * @throws \think\Exception
     */
    public function set_is_accept_yx()
    {
        $is_accept_yx = $this->request->request('is_accept_yx');
        $user_id = $this->request->request('user_id');
        $result = false;
        Db::startTrans();
        try {
            $result = User::where(['id'=>$user_id])->update(['is_accept_yx'=>$is_accept_yx]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 指定团长
     *
     * @return string
     * @throws \think\Exception
     */
    public function user_list_add($ids = null)
    {
        if (false === $this->request->isPost()) {
            $user_list =  User::field("nickname,id")->where(['is_task'=>0,'status'=>1])->select();
            $this->view->assign('user_list', $user_list);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = User::where(['id'=>['in',$params['user_id']]])->update(['is_task'=>1,'task_time'=>time()]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

    /**
     * 人设编辑
     *
     * @return string
     * @throws \think\Exception
     */
    public function set_character_type($id = null)
    {
        $status = $this->request->request('status');
        $result = false;
        Db::startTrans();
        try {
            $result = User::where(['id'=>$id])->update(['character_type'=>$status]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

    


    
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function product_add()
    {
        if (false === $this->request->isPost()) {
            $category=ProductCategory::where(array('pid'=>1,'status'=>'normal'))->order('weigh desc')->select();
            $this->view->assign('category_list', $category);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        if(empty($params['title'])){
            $this->error('标题不可为空');
        }
        if(empty($params['category_id'])){
            $this->error('请选择分类');
        }
        if($params['peisong'] == '0,1' && empty($params['weight'])){
            $this->error('请选择重量');
        }
        if(empty($params['imgs'])){
            $this->error('请选择图片');
        }
        $imgs_arr = explode(',',$params['imgs']);
        $params['video_img'] = $imgs_arr[0];

        $list = User::where(['virtual_status'=>1,'status'=>1])->select();
        if(!$list){
            $this->error('虚拟用户错误'); 
        }
        $UserAddress = $this->get_user($list);
        $params['user_id'] = $UserAddress['user_id'];
        $params['province'] = $UserAddress['province'];
        $params['city'] = $UserAddress['city'];
        $params['area'] = $UserAddress['district'];
        $params['name'] = $UserAddress['name'];
        $params['phone'] = $UserAddress['mobile'];
        $params['status'] = 1;
        $params['add_time'] = time();
        $params['want_count'] = rand(1,5);

        $fid = SArea::where(['name'=>['like','%'.$params['province'].'%']])->value('id');
        if($params['city'] != '市辖区'){
            $fid = SArea::where(['name'=>['like','%'.$params['city'].'%'],'fid'=>$fid])->value('id');
        }
        $info = SArea::where(['name'=>['like','%'.$params['area'].'%'],'fid'=>$fid])->find();
        $params['longitude'] = $info['lng'];
        $params['latitude'] = $info['lat'];
        if(!$params['longitude'] || !$params['latitude']){
			$params['longitude'] = '';
			$params['latitude'] = '';
		}
        $id = Product::insertGetId($params);
        if($id){
            $this->success('操作成功','',$id);
        }else{
            $this->error('操作失败');
        }
    }

    public function get_user($list)
    {
        $user = $list[rand(0,count($list)-1)];
        $UserAddress = UserAddress::where(['user_id'=>$user['id']])->order('is_default desc')->find();
        if(!$UserAddress){
            return $this->get_user($list);
        }else{
            return $UserAddress;
        }
    }
     /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->redirect('product_add');
            return;
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
           

            if($row['end_time']){
                $row['end_time'] = date('Y-m-d H:i:s',$row['end_time']);
            }else{
                $row['end_time'] = '';
            }
            $Product = Product::where(['id'=>$row['product_id']])->find();
            $row['product_name'] = '';
            $row['product_status'] = '';
            if($Product){
                $row['product_name'] = $Product['title'];
                if($Product['is_sale'] == 1){
                    $row['product_status'] = '已售出';
                }else{
                    if($Product['status'] == 0){
                        $row['product_status'] = '待审核';
                    }elseif($Product['status'] == 1){
                        $row['product_status'] = '已上架';
                    }elseif($Product['status'] == -1){
                        $row['product_status'] = '已下架';
                    }elseif($Product['status'] == -2){
                        $row['product_status'] = '已删除';
                    }
                }
            }
            $this->view->assign('row', $row);
            $user_list =  User::field("nickname,id")->where(['is_task'=>1])->select();
            $this->view->assign('user_list', $user_list);
            if($this->group_id == 7){
                $type_arr = Shop::where(['status'=>1,'id'=>['in',$this->admin['shop_ids']]])->column('name');
            }else{
                $type_arr = Shop::where(['status'=>1])->column('name');
            }
            $this->view->assign('type_arr', $type_arr);

            $is_province = Shop::where(['admin_id'=>$this->admin['id']])->value('is_province');
            $this->view->assign('is_province', $is_province);
            //查询所有的省
            $AreaList = Area::field("name")->where(['pid'=>0])->select();
            $this->view->assign('AreaList', $AreaList);
            
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if($this->group_id == 6 && $row['status'] != -3){
            $this->error('该状态无法编辑');
        }
        $result = false;
        Db::startTrans();
        try {
            if($row['end_time']){
                $row['end_time'] = date('Y-m-d H:i:s',$row['end_time']);
            }
            if(isset($params['status']) && $params['status'] == 1){
                //需要重新发布商品
                $arr = [
                    'add_time' => time(),
                    'title'=>$params['title'],
                    'content'=>$params['content'],
                    'imgs'=>$params['imgs'],
                    'product_id'=>$params['product_id'],
                    'type'=>$params['type'],
                    'beizhu'=>$params['beizhu'],
                    'shop_id'=>$row['shop_id'],
                    'task_type'=>$row['task_type']
                ];

                
                if(!empty($params['province'][0])){
                    $arr['province'] = $params['province'][0];
                }
                if($row['shop_id']){
                    //查询商户信息
                    $shop  = Shop::where(['id'=>$row['shop_id']])->find();
                    if($shop && $shop['is_admin_gl'] == 1){
                        //商户上传任务操作
                        $admin_id = 0;
                        if($this->group_id == 7){
                            $admin_id = $this->admin['id'];
                        }
                        if($row['task_type'] == 4){
                            //商户上传任务操作
                            $res = ['tl_title'=>$params['title'],'tl_content'=>$params['title'],'tl_imgs'=>$params['imgs']];
                            $result = shop_add_comment_task($res,$shop);
                        }else{
                            $result = shop_add_task($arr,$shop,$admin_id);
                        }
                        if ($result === false){
                            Db::commit();
                            $this->error('商户余额不足');
                        }
                    }
                }else{
                    $result = DistributeTaskModer::insert($arr);
                }
            }else{
                if(!empty($params['province'][0])){
                    $params['province'] = $params['province'][0];
                }
                //编辑商品
                if(isset($params['status'])){
                    unset($params['status']);
                }
                $result = $row->allowField(true)->save($params);
            }
            
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

     /**
     * 删除
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function del($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if($row['status'] == 0 || $row['status'] == -3){
            //判断是否是商户操作
            if($this->group_id == 6){
                $res = set_shop_task_price($ids,1);
                if(!empty($res['code']) && $res['code'] == 1){
                    $res = $this->model->where(['id'=>$ids])->delete();
                    if (false === $res) {
                        $this->error(__('No rows were updated'));
                    }
                }else{
                    $this->error($res['msg']);
                }
            }else{
                set_shop_task_price($ids,1);
                $res = $this->model->where(['id'=>$ids])->delete();
                if (false === $res) {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->success();
        }else{
            $this->error('当前状态任务不可删除');
        }
        
    }

    //统计浏览数量
    public function statistics_update_status(){
        $id = $this->request->request('id',0);
        $statistics_num = $this->request->request('statistics_num','');
        $info = DistributeTaskModer::where(['id'=>$id,'status'=>3])->find();
        if(!$info){
            $this->error('数据错误');
        }
        Db::startTrans();
        try{
            $res = DistributeTaskModer::where(['id'=>$id])->update(['statistics_num'=>$statistics_num]);
            if(!$res){
                Db::rollback();
                $this->error('操作失败');
            }
            Db::commit();
            $this->success('操作成功');
        }catch (Exception $e) {
            Db::rollback();
            $this->error('操作失败');
        }
    }
    //更改状态
    public function update_status(){
        $id = $this->request->request('id',0);
        $status = $this->request->request('status','');
        $is_illegal = $this->request->request('is_illegal','');
        $remark = $this->request->request('remark','');
        if($is_illegal == 2){
            DistributeTaskModer::where(['id'=>$id])->update(['is_illegal'=>2]);
            $this->success('操作成功');
        }
        //上架
        if($status == 0){
            DistributeTaskModer::where(['id'=>$id])->update(['status'=>0]);
            $this->success('操作成功');
        }elseif($status == -3){//下架
            DistributeTaskModer::where(['id'=>$id])->update(['status'=>-3]);
            $this->success('操作成功');
        }
        $info = DistributeTaskModer::where(['id'=>$id,'status'=>2])->find();
        if(!$info){
            $this->error('数据错误');
        }
        $userInfo = User::where(['id'=>$info['user_id']])->find();
        Db::startTrans();
        try{
            //通过审核
            if($status == 1){
                //完成后分发佣金
                $info = DistributeTaskModer::where(['id'=>$id])->find();
                if($info['task_status'] == 'pinglun' || $info['task_status'] == 'comment_num' ){
                    $price = 0.5;
                }else{
                    //查询佣金规则
                    if($info['type'] != '余享小红书'){
                        $configWhere = ['name'=>'dianshiju'];
                    }else{
                        $configWhere = ['name'=>'distribute'];
                    }
                    $config = Config::where($configWhere)->value('value');
                    $config = json_decode($config,true);
                    $price = 0;
                    if(!empty($config['award'])){
                        $awardArr = $config['award'];
                        $priceArr = $config['price'];
                        foreach ($awardArr as $k=>$award_arr) {
                            if(count($award_arr) == 1){
                                if($info['statistics_num'] > $award_arr[0]){
                                    $price = $priceArr[$k];
                                }
                            }else{
                                if($info['statistics_num'] >= $award_arr[0]  &&  $info['statistics_num'] <=  $award_arr[1]){
                                    $price = $priceArr[$k];
                                }
                            }
                        }
                    }else{
                        $price = $info['price'];
                    }
                }
                $res = DistributeTaskModer::where(['id'=>$id])->update(['status'=>3,'complete_time'=>time(),'price'=>$price]);
                if(!$res){
                    Db::rollback();
                    $this->error('操作失败');
                }

                //查询是否是素材任务
                $OperationTask = OperationTask::where(['status'=>0,'task_id'=>$id])->find();
                if($OperationTask){
                    OperationTask::where(['id'=>$OperationTask['id']])->update(['title'=>$info['user_operation_title'],'content'=>$info['user_content'],'imgs'=>$info['user_imgs'],'status'=>1]);
                    if($OperationTask['issue_type'] == 1){
                        $price = 8;
                    }elseif($OperationTask['issue_type'] == 2){
                        $price = 6;
                    }elseif($OperationTask['issue_type'] == 3){
                        $price = 3;
                    }
                }


                //查看该用户是否是被邀请
                $DistributeTaskInvite = DistributeTaskInvite::where(['invite_id'=>$info['user_id'],'status'=>0])->find();
                if($DistributeTaskInvite){
                    DistributeTaskInvite::where(['id'=>$DistributeTaskInvite['id']])->update(['status'=>1,'price'=>2]);

                    $InviteUser = User::where(['id'=>$DistributeTaskInvite['user_id']])->find();
                    //记录佣金日志
                    $arr = [
                        'user_id'=>$InviteUser['id'],
                        'new_price'=>$InviteUser['task_price'],
                        'price'=>2,
                        'type'=>5,
                        'old_price'=>$InviteUser['task_price']+2,
                        'add_time'=>time()
                    ];
                    DistributeTaskLog::insert($arr);
                    User::where(['id'=>$InviteUser['id']])->update(['task_price'=>$InviteUser['task_price']+2]);
                }

                //通过审核后管理商户余额
                $res = set_shop_task_price($info['id'],2);
              
                if($res['code'] == -1){
                    Db::rollback();
                    $this->error($res['msg']);
                }

                User::where(['id'=>$info['user_id']])->update(['task_price'=>$userInfo['task_price'] + $price]);
                //记录佣金日志
                $arr = [
                    'user_id'=>$info['user_id'],
                    'new_price'=>$userInfo['task_price'],
                    'price'=>$price,
                    'old_price'=>$userInfo['task_price']+$price,
                    'add_time'=>time()
                ];
                DistributeTaskLog::insert($arr);
                
                //发送短信
                send_mobile($userInfo['mobile'],'SMS_464185599');
            }else{
                $res = DistributeTaskModer::where(['id'=>$id])->update(['status'=>-1,'remark'=>$remark]);
                if(!$res){
                    Db::rollback();
                    $this->error('操作失败');
                }
                //发送短信
                send_mobile($userInfo['mobile'],'SMS_464210658');
            }
            Db::commit();
            $this->success('操作成功');
        }catch (Exception $e) {
            Db::rollback();
            $this->error('操作失败');
        }
    }

    /**
     * 查看
     */
    public function withdraw()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = Withdraw::alias('a')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$v) {
                $user = User::field('nickname,is_supervise')->where(['id'=>$v['user_id']])->find();
                $v['nickname'] = $user['nickname'];
                $v['is_supervise'] = $user['is_supervise'];
            }   
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    //更改状态
    public function withdraw_update_status(){
        $id = $this->request->request('id',0);
        $status = $this->request->request('status','');
        $remark = $this->request->request('remark','');
        $info = Withdraw::where(['id'=>$id])->find();
        if(!$info){
            $this->error('操作失败');
        }
        $user = User::where(['id'=>$info['user_id']])->find();
        if(!$user['openid'] && $status == 1){
            $this->error('用户openid错误,操作失败');
        }
        //查询该用户提现金额流水是否正常
        $price_sum = DistributeTaskLog::where(['user_id'=>$user['id']])->sum('price');
        $handingfee = DistributeTaskLog::where(['user_id'=>$user['id']])->sum('handingfee');
        $price_sum = bcadd($price_sum, $handingfee, 2);
        
        if($price_sum != $user['task_price'] && $status == 1){
            $this->error('用户佣金余额异常,操作失败');
        }
        Db::startTrans();
        try{
            //通过审核
            if($status == 1){
                //通过审核给用户打钱
                $WithdrawApi = new WithdrawApi();
                $data = ['out_detail_no'=>$info['orderid'],'transfer_amount'=>(int)bcmul($info['money'],100,2),'transfer_remark'=>'用户提现','openid'=>$user['openid']];
                $resArr = $WithdrawApi->sendredpack([$data],'用户提现',(int)bcmul($info['money'],100,2),'wx84f56a63b9f63e03');
                if(!empty($resArr['batch_status']) &&  $resArr['batch_status'] =='ACCEPTED'){
                    //提现成功
                    $res = Withdraw::where(['id'=>$id])->update(['status'=>'successed','transactionid'=>$resArr['batch_id']]);
                    $arr = [
                        'type'=>'apply',
                        'pay_type'=>'wechat',
                        'order_id'=>$info['orderid'],
                        'out_trade_no'=>$info['orderid'],
                        'createtime'=>time(),
                        'amount'=>$info['money'],
                        'pay_amount'=>$info['money'],
                        'status'=>'success',
                        'pay_json'=>json_encode($resArr),
                        'payment_id'=>$resArr['out_batch_no'],
                        'transaction_id'=>$resArr['batch_id'],
                        'pay_time'=>time(),
                        'user_id'=>$user['id'],
                    ];
                    Payment::insert($arr);
                }else{
                    Db::rollback();
                    $arr = [
                        'type'=>'apply',
                        'pay_type'=>'wechat',
                        'order_id'=>$info['orderid'],
                        'out_trade_no'=>$info['orderid'],
                        'createtime'=>time(),
                        'amount'=>$info['money'],
                        'pay_amount'=>$info['money'],
                        'status'=>'fail',
                        'pay_json'=>json_encode($resArr),
                        'pay_time'=>time(),
                        'user_id'=>$user['id'],
                    ];
                    Payment::insert($arr);
                    if(!empty($resArr['message'])){
                        $this->error($resArr['message']);
                    }else{
                        $this->error('操作失败');
                    }
                }
            }else{
                $res = Withdraw::where(['id'=>$id])->update(['status'=>'rejected','remark'=>$remark]);
                if(!$res){
                    Db::rollback();
                    $this->error('操作失败');
                }
                //拒绝审核给返回用户金额
                $arr = [
                    'user_id'=>$user['id'],
                    'new_price'=>$user['task_price'],
                    'old_price'=>$user['task_price']+$info['money'],
                    'price'=>$info['money'],
                    'type'=>3,
                    'add_time'=>time()
                ];
                DistributeTaskLog::insert($arr);
                User::where(['id'=>$user['id']])->update(['task_price'=>$arr['old_price']]);
            }
            Db::commit();
            $this->success('操作成功');
        }catch (Exception $e) {
           Db::rollback();
           $this->error('操作失败');
        }
    }
    


    /**
     * 任务参数设置
     *
     * @return string
     * @throws \think\Exception
     */
    public function config()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = User::where(['id'=>['in',$params['user_id']]])->update(['is_task'=>1,'task_time'=>time()]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

    //AI生成
    public function getAiChatGpt(){

        //查询商户信息
        $shop = Shop::where(['admin_id'=>$this->admin['id'],'status'=>1])->find();
        if(!$shop){
            $this->error('商户信息错误');
        }
        //查询商户余额或者ai次数是否足够
        /* if($shop['balance'] < 0.05 && $shop['ai_num'] == 0){
            $this->error('商户余额不足,无法使用AI工具');
        } */

	    set_time_limit(0);
		$title = $this->request->request('title','');
		$content = $this->request->request('content','');
		$user_id = $shop['user_id'];
		$shop_id = $shop['id'];

		$content = str_replace(PHP_EOL, '', $content);
		$title = str_replace(PHP_EOL, '', $title);

		$query = '下面我将提供一个中文的内容模板，该内容模板包括“标题”和“内容”两部分，“标题”在20个字以内阐述。请按照模板的标题和内容去生成新的标题和内容，新标题要契合内容，新内容要和模板内容阐述的意思一致，并保留原有的段落结构，新内容的长度也基本跟原内容一致。标题：'.$title.'。内容：'.$content.'。';
		if(!$query){
			$this->error('参数错误');
		}
		$shop = Shop::where(['id'=>$shop_id])->find();
		if(!$shop){
			$this->error('商户信息错误');
		}
		/* if($shop['ai_num'] <= 0 && $shop['balance'] < 0.05){
			$this->error('账户余额不足');
		} */
		$res = get_gpt_data($query,$user_id,$shop_id);
		if($res['code'] == 1){
			$this->success('获取成功','',$res['data']);
		}elseif($res['code'] == -2){
			//重新请求一次
			$query = '注意：请区分“标题”和“内容”两部分!'.$query;
			$res = get_gpt_data($query,$user_id,$shop_id);
			if($res['code'] == 1){
				$this->success('获取成功','',$res['data']);
			}else{
				$this->error('AI生成错误,请重新操作');
			}
		}else{
			$this->error('AI生成错误,请重新操作');
		}
	}


    //获取图片
    public function getImgs(){
        $img = $this->request->request('img','');
        $text = $this->request->request('text','');
        $num = $this->request->request('num',10);

        if($text){
            $data = $this->disposeImg($img,3,$text,$num);
        }else{
            $data = $this->disposeImg($img,2,$text,$num);
        }
        $data['img'] = $img;
        $this->success('获取成功','',$data);
    }
    
    //生成处理后图
	public function disposeImg($background = '',$type = '',$text = '',$num = 1){
	    $is_bj = 0;
        $hash = '';
	    if($background){
	        $is_bj = 1;

            //传了图片 储存哈希值
            $hash = md5_file($background);
	    }
		$background = $background ? $background : $this->request->request('background','');
		$type = $type ? $type : $this->request->request('type',2);
		$text = $text ? $text : $this->request->request('text','');
   
		//未传背景图
		if(!$background){
			$background = Db::name('template')->where(['status'=>1,'type'=>1])->orderRaw('rand()')->limit(1)->value('img');
		}
        
		$background_arr = explode('uploads',$background);
		$background = 'uploads'.$background_arr[1];
       
		$image = \think\Image::open($background);
		$img = 'uploads/invite/'.time().rand(1000, 9999).'.png';
		// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
		$image->thumb(900,1200,\think\Image::THUMB_CENTER)->save($img);
        $ids = '0';
        $bj_ids = '0';
        if($hash){
            $template_ids = TemplateImgLog::where(['content'=>$hash])->column('template_id');
            if($template_ids){
                foreach ($template_ids as $v) {
                    $ids .= ','.$v;
                }
            }
        }

        for ($i=0; $i < $num; $i++) { 
            if($is_bj == 0){
            	$background = Db::name('template')->where(['status'=>1,'type'=>1,'id'=>['neq',$bj_ids]])->orderRaw('rand()')->limit(1)->find();
            	$bj_ids .= ','.$background['id'];
            	$background_arr = explode('uploads',$background['img']);
        		$background = 'uploads'.$background_arr[1];
               
        		$image = \think\Image::open($background);
        		$img = 'uploads/invite/'.time().rand(1000, 9999).'.png';
        		// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
        		$image->thumb(900,1200,\think\Image::THUMB_CENTER)->save($img);
            }
            if($type == 2){
                //获取模版
                $template =  Db::name('template')->where(['status'=>1,'type'=>$type,'id'=>['neq',$ids]])->orderRaw('rand()')->limit(1)->find();	
                $ids .= ','.$template['id'];
                $template_arr = explode('uploads',$template['img']);
                $img1 = 'uploads'.$template_arr[1];
                $image = \think\Image::open($img);
                $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
                $image->water($img1,[0,0])->save($img2);
            }elseif( $type == 3 && $text){
                $len =  mb_strlen($text, 'utf8');
                if($len > 16){
                    $this->error('不可超过16个字');
                }
                if($len > 8){  //两行显示
                    $where = [
                        'status'=>1,
                        'type'=>$type,
                        'pre_line'=>['>=',$len],
                        'line'=>2,
                        'id'=>['neq',$ids]
                    ];
                }else{  //一行显示
                    $where = [
                        'status'=>1,
                        'type'=>$type,
                        'pre_line'=>['>=',$len],
                        'line'=>1,
                        'id'=>['neq',$ids]
                    ];
                }
                //获取模版
                $template =  Db::name('template')->where($where)->orderRaw('rand()')->limit(1)->find();	
                if(!$template){
                    $this->error('操作错误');
                }
                $ids .= ','.$template['id'];
                $template_arr = explode('uploads',$template['img']);
                $img1 = 'uploads'.$template_arr[1];
    
                $image = \think\Image::open($img);
                $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
                $image->water($img1,[0,0])->save($img2);
                
                $image1 = \think\Image::open($img2);
                
                $zt = Db::name('template')->where(['status'=>1,'type'=>5])->orderRaw('rand()')->limit(1)->value('img');
                $zt = ROOT_PATH.$zt;
                
                if($len > 8){  //两行显示
                    $text1 = mb_substr($text, 0, 8,'utf8');
                    $text2 = mb_substr($text, 8, $len,'utf8');
                    
                   
                    if(!$template['location_z']){
                        $fontBox = imagettfbbox($template['size'], 0, $zt, $text1);
                        $template['location_z'] = ceil(450 - ($fontBox[2] / 2));
                    }
                    $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
                    $image1->text($text1,$zt,$template['size'],$template['color'],[$template['location_z'],$template['location_y']])->save($img2);
                    
                    if(!$template['location_z']){
                        $fontBox = imagettfbbox($template['size'], 0, $zt, $text2);
                        $template['location_z'] = ceil(450 - ($fontBox[2] / 2));
                    }
                    $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
                    $image1->text($text2,$zt,$template['size'],$template['color'],[$template['location_z'],$template['location_y']+$template['interval']])->save($img2);
                    
                }else{  //一行显示
                    
                    if(!$template['location_z']){
                        $fontBox = imagettfbbox($template['size'], 0, $zt, $text);
                        $template['location_z'] = ceil(450 - ($fontBox[2] / 2));
                    }
                    $img2 = 'uploads/invite/'.time().rand(1000, 9999).'.png';
                    $image1->text($text,$zt,$template['size'],$template['color'],[$template['location_z'],$template['location_y']])->save($img2);
                }
    
                if($hash){
                    TemplateImgLog::insert(['content'=>$hash,'template_id'=>$template['id'],'add_time'=>time()]);
                }
            }

            $new_url[] = 'https://oa.yuxiang123.cn/'.$img2;
        }
		

        $data['new_url'] = $new_url;
        $data['new_urls'] = implode(',',$new_url);
        return $data;

	}
		

		

}